
package cn.yunyichina.provider.clinic.service.impl;

import cn.yunyichina.provider.clinic.config.Config;
import cn.yunyichina.provider.clinic.constant.BizConstant;
import cn.yunyichina.provider.clinic.dao.FuyinApplyDao;
import cn.yunyichina.provider.clinic.entity.FuyinApply;
import cn.yunyichina.provider.clinic.utils.KdniaoTrackQueryAPI;
import cn.yunyichina.provider.clinic.vo.FinanceExcel;
import cn.yunyichina.provider.clinic.vo.FuyinApplyRequest;
import cn.yunyichina.provider.framework.annotation.validate.ValidateException;
import cn.yunyichina.provider.framework.annotation.validate.Validator;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.data.SpringContextHandler;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.dubbo.service.CacheService;
import cn.yunyichina.provider.framework.dubbo.service.HisifaceService;
import cn.yunyichina.provider.framework.dubbo.service.PayService;
import cn.yunyichina.provider.framework.qiniu.QiniuService;
import cn.yunyichina.provider.framework.utils.ExcelUtil;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.base.Org;
import cn.yunyichina.provider.iface.entity.cache.SessionInfo;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.provider.iface.entity.hisiface.bed.BedRecordsVo;
import cn.yunyichina.provider.iface.entity.hisiface.bed.BedRecordsVoResponse;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.commons.IdCardUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yy.easyhealth.invoke.OutsideInvokeService;
import com.yy.easyhealth.invoke.dto.Request;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.util.*;

@Service
public class FuyinServiceImpl {
    private Logger logger = LoggerFactory.getLogger(FuyinServiceImpl.class);

    @Autowired
    private FuyinApplyDao fuyinApplyDao;
    @Resource
    private Properties yaml;
    private static String PAY_STATUS ="{\"0\":\"未支付\",\"1\":\"支付成功\",\"2\":\"支付失败\",\"3\":\"异常订单\",\"4\":\"微信返回异常\",\"7\":\"同步退费成功\",\"8\":\"同步退费失败\"}";
    private static String APPLY_STATUS ="{\"0\":\"患者证件审核未处理\",\"1\":\"患者病案复印已发送\",\"2\":\"患者证件审核不通过\",\"3\":\"患者证件审核已通过\",\"4\":\"患者病案已打印\"}";
    private static String USE_FOR ="{\"1\":\"进行医保报销\",\"2\":\"进行保险业务\",\"3\":\"保存\",\"4\":\"其他\"}";
    private static String RECEIVE_TYPE ="{\"1\": \"快递\",\"2\": \"医院自取(本人)\",\"3\":\"医院自取(代理申请人)\"}\n";
    private static String copyJson = "{\"all\": \"所有\",\"1\": \"出院记录\",\"2\": \"入院记录\",\"3\": \"手术同意书\",\"4\": \"麻醉同意书\",\"5\": \"手术记录单\",\"6\": \"特殊检查同意书\",\"7\": \"护理记录\",\"8\": \"检查报告单\",\"9\": \"医学影像检查报告\",\"10\": \"病理检查报告\",\"11\": \"其它检查报告\",\"12\": \"医嘱单\",\"13\": \"体温单\",\"14\": \"首页\",\"15\": \"麻醉记录\",\"16\": \"知情同意书\",\"17\": \"病程记录\",\"18\": \"围产大卡\",\"19\": \"分娩记录\",\"20\": \"足印记录\",\"21\": \"死亡证明\",\"22\": \"入院登记卡\",\"23\": \"条码\",\"24\": \"整份病历\",\"25\": \"手术记录\",\"26\": \"病种患者护理记录\",\"27\": \"输入治疗知情同意书\"}\n";

    /**
     * yyt.clinic.fuyin.apply.save - 复印申请提交
     * @param data
     * @param sessionId
     * @return
     */
    public Response saveFuyinApply(String data, String sessionId, String appId) {
        logger.info("saveApply, request data=" + data + ", sessionId=" + sessionId);
        Response response = new Response();
        FuyinApplyRequest applyRequest = JsonUtils.parseObject(data, FuyinApplyRequest.class);

        try {
            Validator.getInstance().validate(applyRequest);
        } catch (ValidateException ex) {
            logger.info(" 数据校验失败:" + ex.getMessage() + "|入参:" + data + "！");
            logger.error("error", ex);
            response.setResultCodeAndMessage("3001", "数据校验失败:" + ex.getMessage() + "！");
            return response;
        }

        try {
            FuyinApply apply = new FuyinApply();
            BeanUtils.copyProperties(applyRequest, apply);

            apply.setApplyId(UUID.randomUUID().toString().replaceAll("-", ""));
            apply.setCreateTime(BizConstant.YYYYMMDDHHMMSS.format(new Date()));
            apply.setOrderNo(CacheService.generateOrderNum(6, 1));
            apply.setApplyStatus(BizConstant.APPLY_STATUS_INIT);
            apply.setRefundFee(0);
            logger.info("saveApply, apply=" + JSONObject.toJSONString(apply));
            fuyinApplyDao.insert(apply);
            
            //插入订单进库,
            List<OrderExtVo> orders = new ArrayList<OrderExtVo>();
            OrderExtVo order=new OrderExtVo();
            order.setId(PKGenerator.generateId());
            order.setOrderNo(apply.getOrderNo());
            
            Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("org_code", apply.getHospitalCode());
            logger.info("复印申请提交查询外部接口, 调base模块, 查询医院信息入参request="
                    + JSON.toJSONString(paramMap));
            Response response1 = BaseService.callUnderlineFromInternal("yyt.base.branchhospital.org.list",
                    JSON.toJSONString(paramMap));
            logger.info("复印申请提交查询外部接口, 调base模块, 查询医院信息返回response="
                    + JSONObject.toJSONString(response1));
            if (!"0".equals(response1.getResultCode())) {
                response.setResultCodeAndMessage("3000", "没有org_code对应的机构信息！");
                return response;
            }
            List<Org> orgList = JsonUtils.parseArray(response1.getResult(), Org.class);
            if (CollectionUtils.isEmpty(orgList)) {
                response.setResultCodeAndMessage("3002", "不存在[org_code:" + apply.getHospitalCode() + "]对应的医院信息！");
                return response;
            }
            Org org = orgList.get(0);

            
            order.setOrgId(org.getId());
            order.setOrgName(org.getOrgName());
            order.setOrgCode(org.getOrgCode());
            
            //由于以前的病案复印没有定义应用code，所以所有的数据都挂在云医科技--》云医通下面(作废，改为从appId换取)
//            order.setPlatformId("1d946fbaa26b11e6951000163e00175d");
//            order.setPlatformName("广州云医科技有限公司");
//            order.setPlatformCode("yykj");
//            order.setPlatformOrgAppCode("yytc06514ff54dbe32d");
//            order.setPlatformOrgAppName("云医通");
            Map<String, String> map = new HashMap<String, String>();
            map.put("org_app_code", appId);
            logger.info("【复印申请提交】, 就诊卡号" + applyRequest.getPatCardNo() + ", 调base模块, 查询组织应用接口入参request="
                    + JSON.toJSONString(map));
            Response baseRes = BaseService.callUnderlineFromInternal(sessionId, "yyt.base.orgapp.get",
                    JsonUtils.toJsonString(map));
            logger.info("【复印申请提交】, 就诊卡号" + applyRequest.getPatCardNo() + ", 调base模块, 查询组织应用接口返回response="
                    + JSON.toJSONString(baseRes));
            if ("0".equals(baseRes.getResultCode())) {
                JSONObject o = JSONObject.parseObject(baseRes.getResult());
                order.setPlatformId(o.getString("org_id"));
                order.setPlatformName(o.getString("org_name"));
                order.setPlatformOrgAppCode(o.getString("org_app_code"));// 平台应用编码
                order.setPlatformCode(o.getString("org_code"));
                order.setPlatformOrgAppName(o.getString("org_app_name"));
            }else{
                response.setResultCodeAndMessage("3000", "没有[app_id:" + appId + "]对应的组织应用信息！");
                return response;
            }

            order.setBranchCode("");
            order.setBranchId("");
            order.setBranchName("");
            order.setDeptId("");
            order.setDeptName(apply.getAdmissionDeptName());
            order.setDeptCode("");
            order.setOrderStatus((short)1);
            order.setPayStatus((short)1);
            order.setOrderType((short)6);
            order.setUserId("");
            order.setUserName(apply.getPatName());
            order.setUserMobile(apply.getApplyUserMobile());
            order.setMedicalCardType((short)apply.getPatCardType().intValue());
            order.setMedicalCardNo(apply.getPatCardNo());
            order.setIdCardType((short)1);
            order.setIdCardNo(apply.getIdcardNo());
            order.setUserAddress(apply.getExpressAddress());
            order.setUserSex(IdCardUtils.getSexFlagByIdCard(apply.getIdcardNo()));//这个可以从身份证获取
            order.setInsuranceCardNo("");
            order.setDoctorName("");
            order.setDoctorCode("");
            order.setDoctorTitle("");
            order.setOutOrderNo("");
            order.setHisOrderNo("");
            order.setPayMode((short)11);
            order.setInsuranceMode((short)0);
            order.setOpenId("");
//            order.setPayCode("WXAPP");    支付完才能获取到, 这里不再做赋值
            order.setIsInsurance((short)0);
            order.setPayAmount(apply.getPayFee());
            order.setPayRealAmount(apply.getPayFee());
            order.setAccountAmount(0);
            order.setMedicareAmount(0);
            order.setInsuranceAmount(0);
            order.setInsuranceRealAmount(0);
            order.setTotalAmount(apply.getPayFee());
            order.setTotalRealAmount(apply.getPayFee());
            order.setPayUserId("");
            order.setPayUserName("");
            order.setPayAppId(apply.getAppId());
            order.setCollectors("");
            order.setPromoterId("");
            order.setMzFeeId("");
            order.setReserveNo("");
            order.setCreatedTime(DateUtils.dateToString(new Date()));
            orders.add(order);
            
      
            logger.info("复印申请提交, 调用base模块, 批量添加订单接口入参request="+ JSON.toJSONString(orders));
            BaseService.callUnderlineFromInternal(sessionId, "yyt.base.order.out.add", JsonUtils.toJsonString(orders));
           
            response.setResultCodeAndMessage("0", "保存成功");
            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("apply_id", apply.getApplyId());
            resultMap.put("order_no", apply.getOrderNo());
            response.setResult(JsonUtils.toJsonString(resultMap));
        } catch (Exception ex) {
            logger.error("error", ex);
            response.setResultCodeAndMessage("-1", "保存失败");
            return response;
        }
        return response;
    }

    /**
     * yyt.clinic.fuyin.my.apply.list -复印申请记录
     * @param data
     * @param sessionId
     * @return
     */
    public Response listFuyinMyApply(String data, String sessionId) {
        logger.info("listMyApply, request data=" + data + ", sessionId=" + sessionId);
        Response response = new Response();
        FuyinApplyRequest applyRequest = JsonUtils.parseObject(data, FuyinApplyRequest.class);

        if (StringUtils.isBlank(applyRequest.getApplyUserId())) {
            logger.info("listMyApply, request userid is null");
            response.setResultCodeAndMessage("3001", "请求user_id为空");
            return response;
        }

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("applyUserId", applyRequest.getApplyUserId());
        logger.info("listMyApply, paramMap=" + JsonUtils.toJsonString(paramMap));
        List<FuyinApply> list = fuyinApplyDao.selectByUserId(paramMap);
        logger.info("listMyApply, list=" + JsonUtils.toJsonString(list));
        response.setResult(JsonUtils.toJsonString(list));
        return response;
    }

    /**
     * yyt.clinic.fuyin.untreated.apply.list -复印所有未处理申请
     * @param data
     * @param sessionId
     * @return
     */
    public Response listFuyinUntreatedApply(String data, String sessionId) {
        logger.info("listUntreatedApply, request data=" + data + ", sessionId=" + sessionId);
        Response response = new Response();
//        if (!"1".equals(CacheService.getSessionKey(sessionId, "clinic:fuyin:isLogin"))) {
//            response.setResultCodeAndMessage("3006", "操作失败，请先登录。");
//            return response;
//        }
        FuyinApplyRequest applyRequest = JsonUtils.parseObject(data, FuyinApplyRequest.class);
        if (applyRequest.getPageSize() == null) {
            logger.info("listUntreatedApply, request PageSize is null");
            response.setResultCodeAndMessage("3001", "请求page_size为空");
            return response;
        }
        
        if (applyRequest.getPageNum() == null) {
            logger.info("listUntreatedApply, request PageNum is null");
            response.setResultCodeAndMessage("3001", "请求page_num为空");
            return response;
        }
        
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("pageSize", applyRequest.getPageSize());
        paramMap.put("pageNum", applyRequest.getPageNum());
        if (StringUtils.isNotBlank(applyRequest.getBeginTime())) {
            paramMap.put("beginTime", applyRequest.getBeginTime());
        }
        if (StringUtils.isNotBlank(applyRequest.getEndTime())) {
            paramMap.put("endTime", applyRequest.getEndTime());
        }
        paramMap.put("applyStatus", applyRequest.getApplyStatus());
        paramMap.put("payStatus", applyRequest.getPayStatus());
        if (StringUtils.isNotBlank(applyRequest.getOrderNo())) {
            paramMap.put("orderNo", applyRequest.getOrderNo());
        }
        if (StringUtils.isNotBlank(applyRequest.getAgtOrderNum())) {
            paramMap.put("agtOrderNum", applyRequest.getAgtOrderNum());
        }
        if (StringUtils.isNotBlank(applyRequest.getPatName())) {
            paramMap.put("patName", applyRequest.getPatName());
        }
        if (StringUtils.isNotBlank(applyRequest.getAdmissionNo())) {
            paramMap.put("admissionNo", applyRequest.getAdmissionNo());
        }
        if (StringUtils.isNotBlank(applyRequest.getHospitalCode())) {
            paramMap.put("hospitalCode", applyRequest.getHospitalCode());
        }
        logger.info("listUntreatedApply, applyRequest=" + JsonUtils.toJsonString(applyRequest));
        logger.info("listUntreatedApply, paramMap=" + JsonUtils.toJsonString(paramMap));
        List<FuyinApply> list = fuyinApplyDao.selectUntreated(paramMap);
        logger.info("listUntreatedApply, list=" + JsonUtils.toJsonString(list));
        
        Long count = fuyinApplyDao.selectUntreatedCount(paramMap);
        logger.info("listUntreatedApply, count=" + count);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("list", JsonUtils.toJsonString(list));
        resultMap.put("page_size", applyRequest.getPageSize());
        resultMap.put("page_num", applyRequest.getPageNum());
        resultMap.put("count", count);
        response.setResult(JsonUtils.toJsonString(resultMap));
        return response;
    }
    
    /**
     * yyt.clinic.fuyin.treated.apply.list -复印所有已处理申请
     * @param data
     * @param sessionId
     * @return
     */
    public Response listFuyinTreatedApply(String data, String sessionId) {
        logger.info("listTreatedApply, request data=" + data + ", sessionId=" + sessionId);
        Response response = new Response();
//        if (!"1".equals(CacheService.getSessionKey(sessionId, "clinic:fuyin:isLogin"))) {
//            response.setResultCodeAndMessage("3006", "操作失败，请先登录。");
//            return response;
//        }
        
        FuyinApplyRequest applyRequest = JsonUtils.parseObject(data, FuyinApplyRequest.class);
        if (applyRequest.getPageSize() == null) {
            logger.info("listUntreatedApply, request PageSize is null");
            response.setResultCodeAndMessage("3001", "请求page_size为空");
            return response;
        }
        
        if (applyRequest.getPageNum() == null) {
            logger.info("listUntreatedApply, request PageNum is null");
            response.setResultCodeAndMessage("3001", "请求page_num为空");
            return response;
        }
        
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("pageSize", applyRequest.getPageSize());
        paramMap.put("pageNum", applyRequest.getPageNum());
        if (StringUtils.isNotBlank(applyRequest.getBeginTime())) {
            paramMap.put("beginTime", applyRequest.getBeginTime());
        }
        if (StringUtils.isNotBlank(applyRequest.getEndTime())) {
            paramMap.put("endTime", applyRequest.getEndTime());
        }
        paramMap.put("applyStatus", applyRequest.getApplyStatus());
        paramMap.put("payStatus", applyRequest.getPayStatus());
        if (StringUtils.isNotBlank(applyRequest.getOrderNo())) {
            paramMap.put("orderNo", applyRequest.getOrderNo());
        }
        if (StringUtils.isNotBlank(applyRequest.getAgtOrderNum())) {
            paramMap.put("agtOrderNum", applyRequest.getAgtOrderNum());
        }
        if (StringUtils.isNotBlank(applyRequest.getPatName())) {
            paramMap.put("patName", applyRequest.getPatName());
        }
        if (StringUtils.isNotBlank(applyRequest.getAdmissionNo())) {
            paramMap.put("admissionNo", applyRequest.getAdmissionNo());
        }
        if (StringUtils.isNotBlank(applyRequest.getHospitalCode())) {
            paramMap.put("hospitalCode", applyRequest.getHospitalCode());
        }
        logger.info("listTreatedApply, applyRequest=" + JsonUtils.toJsonString(applyRequest));
        logger.info("listTreatedApply, paramMap=" + JsonUtils.toJsonString(paramMap));
        List<FuyinApply> list = fuyinApplyDao.selectTreated(paramMap);
        logger.info("listTreatedApply, list=" + JsonUtils.toJsonString(list));
        
        Long count = fuyinApplyDao.selectTreatedCount(paramMap);
        logger.info("listTreatedApply, count=" + count);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("list", JsonUtils.toJsonString(list));
        resultMap.put("page_size", applyRequest.getPageSize());
        resultMap.put("page_num", applyRequest.getPageNum());
        resultMap.put("count", count);
        response.setResult(JsonUtils.toJsonString(resultMap));
        return response;
    }

    /**
     * yyt.clinic.fuyin.apply.treate -复印申请处理
     * @param data
     * @param sessionId
     * @return
     */
    public Response treateFuyinApply(String data, String sessionId) {
        logger.info("treateApply, request data=" + data + ", sessionId=" + sessionId);
        Response response = new Response();
//        if (!"1".equals(CacheService.getSessionKey(sessionId, "clinic:fuyin:isLogin"))) {
//            response.setResultCodeAndMessage("3006", "操作失败，请先登录。");
//            return response;
//        }

        SessionInfo sessions = CacheService.getSessionInfo(sessionId);
        if (null == sessions) {
            response.setResultCodeAndMessage("1101", "用户信息为空，请先登录");
            return response;
        }
        
        FuyinApplyRequest applyRequest = JsonUtils.parseObject(data, FuyinApplyRequest.class);

        if (StringUtils.isBlank(applyRequest.getApplyId())) {
            logger.info("treateApply, request ApplyId is null");
            response.setResultCodeAndMessage("3001", "请求apply_id为空");
            return response;
        }

        if (applyRequest.getApplyStatus() == null) {
            logger.info("treateApply, request ApplyStatus is null");
            response.setResultCodeAndMessage("3001", "请求apply_status为空");
            return response;
        }
        
        String[] applyIds = applyRequest.getApplyId().split(","); 
        for (String applyId : applyIds) {
            try {
                FuyinApply apply = new FuyinApply();
                if (applyRequest.getApplyStatus().intValue() == BizConstant.APPLY_STATUS_SENDED
                        || applyRequest.getApplyStatus().intValue() == BizConstant.APPLY_STATUS_PRINTED) {
                    if (applyRequest.getFuyinFee() == null && applyRequest.getExpressFee() != null) {
                        logger.info("treatApply, request FuyinFee is null");
                        response.setResultCodeAndMessage("3001", "请求fuyin_fee为空");
                        return response;
                    }
                    apply.setFuyinFee(applyRequest.getFuyinFee());
                    apply.setExpressFee(applyRequest.getExpressFee());
                    apply.setExpressName(applyRequest.getExpressName());
                    apply.setExpressOrderNo(applyRequest.getExpressOrderNo());
                }
//                else if (applyRequest.getApplyStatus().intValue() == BizConstant.APPLY_STATUS_PHOTO_FAIL) {
//                    apply.setApplyContent(applyRequest.getApplyContent());
//                }
                apply.setApplyId(applyId);
                apply.setApplyStatus(applyRequest.getApplyStatus());
                apply.setApplyTime(BizConstant.YYYYMMDDHHMMSS.format(new Date()));

                apply.setApprovalBy(sessions.getUserName());
                apply.setApplyContent(applyRequest.getApplyContent());

                logger.info("treatApply, apply=" + JSONObject.toJSONString(apply));
                fuyinApplyDao.update(apply);

                response.setResultCodeAndMessage("0", "更新成功");
            } catch (Exception ex) {
                logger.error("error", ex);
                response.setResultCodeAndMessage("-1", "更新失败");
            }
        }

        return response;
    }
    
    /**
     * yyt.clinic.fuyin.imgs.upload -复印上传照片
     * @param data
     * @param sessionId
     * @return
     */
    public Response uploadFuyinImgs(String data, String sessionId) {
        logger.info("uploadImgs, request data=" + data + ", sessionId=" + sessionId);
        Response response = new Response();
        FuyinApplyRequest applyRequest = JsonUtils.parseObject(data, FuyinApplyRequest.class);

        if (StringUtils.isBlank(applyRequest.getApplyId())) {
            logger.info("uploadImgs, request ApplyId is null");
            response.setResultCodeAndMessage("3001", "请求apply_id为空");
            return response;
        }

        if (applyRequest.getImgUrls() == null) {
            logger.info("uploadImgs, request ImgUrls is null");
            response.setResultCodeAndMessage("3001", "请求img_urls为空");
            return response;
        }

        try {
            FuyinApply apply = new FuyinApply();
            apply.setImgUrls(applyRequest.getImgUrls());
            apply.setApplyId(applyRequest.getApplyId());

            logger.info("treatApply, apply=" + JSONObject.toJSONString(apply));
            fuyinApplyDao.update(apply);

            response.setResultCodeAndMessage("0", "更新成功");
        } catch (Exception ex) {
            logger.error("error", ex);
            response.setResultCodeAndMessage("-1", "更新失败");
            return response;
        }

        return response;
    }

    /**
     * yyt.clinic.fuyin.userimgs.upload -复印上传照片
     * @param data
     * @param sessionId
     * @return
     */
    public Response uploadFuyinUserimgs(String data, String sessionId) {
        logger.info("uploadImgs, request data=" + data + ", sessionId=" + sessionId);
        Response response = new Response();
        FuyinApplyRequest applyRequest = JsonUtils.parseObject(data, FuyinApplyRequest.class);

        if (StringUtils.isBlank(applyRequest.getApplyId())) {
            logger.info("uploadImgs, request ApplyId is null");
            response.setResultCodeAndMessage("3001", "请求apply_id为空");
            return response;
        }

        if (applyRequest.getImgUrls() == null) {
            logger.info("uploadImgs, request ImgUrls is null");
            response.setResultCodeAndMessage("3001", "请求img_urls为空");
            return response;
        }

        try {
            FuyinApply apply = new FuyinApply();
            apply.setImgUrls(applyRequest.getImgUrls());
            apply.setApplyId(applyRequest.getApplyId());

            logger.info("treatApply, apply=" + JSONObject.toJSONString(apply));
            fuyinApplyDao.update(apply);

            response.setResultCodeAndMessage("0", "更新成功");
        } catch (Exception ex) {
            logger.error("error", ex);
            response.setResultCodeAndMessage("-1", "更新失败");
            return response;
        }

        return response;
    }
    
    /**
     * yyt.clinic.fuyin.apply.info.get -复印信息查询
     * @param data
     * @param sessionId
     * @return
     */
    public Response getFuyinApplyInfo(String data, String sessionId) {
        logger.info("getFuyinApplyInfo, request data=" + data + ", sessionId=" + sessionId);
        Response response = new Response();
        FuyinApplyRequest applyRequest = JsonUtils.parseObject(data, FuyinApplyRequest.class);

        if (StringUtils.isBlank(applyRequest.getApplyId())) {
            logger.info("getFuyinApplyInfo, request ApplyId is null");
            response.setResultCodeAndMessage("3001", "请求apply_id为空");
            return response;
        }

        try {
            FuyinApply apply = fuyinApplyDao.selectById(applyRequest.getApplyId());
            response.setResult(JsonUtils.toJsonString(apply));
            response.setResultCodeAndMessage("0", "查询成功");
        } catch (Exception ex) {
            logger.error("error", ex);
            response.setResultCodeAndMessage("-1", "查询失败");
            return response;
        }

        return response;
    }
    
    /**
     * yyt.clinic.fuyin.family.list -复印家人列表
     * @param data
     * @param sessionId
     * @return
     */
    public Response listFuyinFamily(String data, String sessionId) {
        logger.info("listFuyinFamily, request data=" + data + ", sessionId=" + sessionId);
        Response response = new Response();
        
        OutsideInvokeService service = SpringContextHandler.getBean("outsideInvokeService");
        JSONObject jsonObj = JsonUtils.parseObject(data);
        
        Request r = new Request();
        r.setMethodCode("getFamiliesByUserIdAndHospitalCode");
        r.setResponseType("1");
        r.setParams("<userId>" + jsonObj.getString("userId") + "</userId><hospitalCode>"
                + jsonObj.getString("hospitalCode") + "</hospitalCode>");
        
        com.yy.easyhealth.invoke.dto.Response familiesResponse = service.openService(r);
        logger.info("listFuyinFamily, familiesResponse="+JSON.toJSONString(familiesResponse));
        logger.info("listFuyinFamily, list=" + JsonUtils.toJsonString(familiesResponse.getResult()));
        response.setResult(JsonUtils.toJsonString(familiesResponse.getResult()));
        return response;
    }
    
    /**
     * yyt.clinic.fuyin.bed.records.get - 复印获取住院信息
     * @param data
     * @param sessionId
     * @return
     */
    public Response getFuyinBedRecords(String data, String sessionId) {
        logger.info("getFuyinBedRecords, request data=" + data + ", sessionId=" + sessionId);
        Response response = new Response();
        ResCommon<List<BedRecordsVoResponse>> list = HisifaceService.getHisifaceClient().getBedRecords(JsonUtils.parseObject(data,BedRecordsVo.class));
        String strJsonList = JsonUtils.toJsonString(list);
        logger.info("getFuyinBedRecords, list=" + strJsonList);
        response.setResult(strJsonList);
        return response;
    }
    
    /**
     * yyt.clinic.fuyin.pay.status.update -复印支付结果更新
     * @param data
     * @param sessionId
     * @return
     */
    public Response updateFuyinPayStatus(String data, String sessionId) {
        logger.info("updateFuyinPayStatus, request data=" + data + ", sessionId=" + sessionId);
        Response response = new Response();
        FuyinApplyRequest applyRequest = JsonUtils.parseObject(data, FuyinApplyRequest.class);

        if (StringUtils.isBlank(applyRequest.getOrderNo())) {
            logger.info("updateFuyinPayStatus, request OrderNo is null");
            response.setResultCodeAndMessage("3001", "请求order_no为空");
            return response;
        }

        if (applyRequest.getPayStatus() == null) {
            logger.info("updateFuyinPayStatus, request PayStatus is null");
            response.setResultCodeAndMessage("3001", "请求pay_status为空");
            return response;
        }

        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("payStatus", applyRequest.getPayStatus());
            paramMap.put("orderNo", applyRequest.getOrderNo());
            paramMap.put("payContent", applyRequest.getPayContent());
            if (applyRequest.getRefundFee() != null) {
                paramMap.put("refundFee", String.valueOf(applyRequest.getRefundFee().intValue()));
            }
            logger.info("updateFuyinPayStatus, paramMap=" + JSONObject.toJSONString(paramMap));
            fuyinApplyDao.updateByOrderNo(paramMap);
            
            if(applyRequest.getPayStatus()==7){
            	 String orderNo=applyRequest.getOrderNo();
            	 Map<String, String> map = new HashMap<String, String>();
                 map.put("order_no", orderNo);
                 logger.info("复印支付结果更新, 订单号" + orderNo + ", 调base模块, 查询订单信息入参request=" + JSONObject.toJSONString(map));
                 Response ordResponse = BaseService.callUnderlineFromInternal("yyt.base.order.by.order.no.out.get",
                         JsonUtils.toJsonString(map));
                 logger.info(
                         "复印支付结果更新, 订单号" + orderNo + ", 调base模块, 查询订单信息返回response=" + JSONObject.toJSONString(ordResponse));
                 if (!"0".equals(ordResponse.getResultCode())) {
                     logger.info("复印支付结果更新, 订单号" + orderNo + ", 调base模块, 查询订单信息失败，未找到对应的订单信息");
                 }else{
                	 OrderExtVo order = JsonUtils.parseObject(ordResponse.getResult(), OrderExtVo.class);
                     if(applyRequest.getRefundFee().intValue()==order.getTotalAmount().intValue()){
                    	 order.setPayStatus((short)7);
                    	 order.setOrderStatus((short)7);;
                     }else{
                    	 order.setPayStatus((short)8);
                     }
                	 
                     logger.info("复印支付结果更新, 订单号" + orderNo + ", 调base模块, 更新订单信息入参request=" + JSONObject.toJSONString(order));
                     BaseService.callUnderlineFromInternal("yyt.base.order.update", JsonUtils.toJsonString(order));
                 }
            }
            response.setResultCodeAndMessage("0", "更新成功");
        } catch (Exception ex) {
            logger.error("error", ex);
            response.setResultCodeAndMessage("-1", "更新失败");
            return response;
        }

        return response;
    }
    
    /**
     * yyt.clinic.fuyin.apply.login -复印登录
     * @param data
     * @param sessionId
     * @return
     */
    public Response loginFuyinApply(String data, String sessionId) {
        logger.info("loginFuyinApply, request data=" + data + ", sessionId=" + sessionId);
        Response response = new Response();
        FuyinApplyRequest applyRequest = JsonUtils.parseObject(data, FuyinApplyRequest.class);
        
        if (StringUtils.isBlank(applyRequest.getUsername())) {
            logger.info("loginFuyinApply, request Username is null");
            response.setResultCodeAndMessage("3001", "请求username为空");
            return response;
        }

        if (StringUtils.isBlank(applyRequest.getPassword())) {
            logger.info("loginFuyinApply, request Password is null");
            response.setResultCodeAndMessage("3001", "请求password为空");
            return response;
        }
        
        if("admin".equals(applyRequest.getUsername()) && "e10adc3949ba59abbe56e057f20f883e".equals(applyRequest.getPassword())) {
            CacheService.setSessionKey(sessionId, "clinic:fuyin:isLogin", "1");
            response.setResultCodeAndMessage("0", "登录成功");
        } else {
            response.setResultCodeAndMessage("-1", "登录失败，账号或密码错误。");
        }
        
        return response;
    }
    
    /**
     * yyt.clinic.fuyin.apply.logout -复印登出
     * @param data
     * @param sessionId
     * @return
     */
    public Response logoutFuyinApply(String data, String sessionId) {
        logger.info("logoutFuyinApply, request data=" + data + ", sessionId=" + sessionId);

        Response response = new Response();
        FuyinApplyRequest applyRequest = JsonUtils.parseObject(data, FuyinApplyRequest.class);

        if (StringUtils.isBlank(applyRequest.getUsername())) {
            logger.info("loginFuyinApply, request Username is null");
            response.setResultCodeAndMessage("3001", "请求username为空");
            return response;
        }

        CacheService.setSessionKey(sessionId, "clinic:fuyin:isLogin", "0");
        response.setResultCodeAndMessage("0", "登出成功");

        return response;
    }
    
    /**
     * yyt.clinic.fuyin.express.info.get -复印获取住院信息
     * @param data
     * @param sessionId
     * @return
     */
    public Response getFuyinExpressInfo(String data, String sessionId) {
        logger.info("getFuyinExpressInfo, request data=" + data + ", sessionId=" + sessionId);

        Response response = new Response();
        FuyinApplyRequest applyRequest = JsonUtils.parseObject(data, FuyinApplyRequest.class);

        if (StringUtils.isBlank(applyRequest.getExpressName())) {
            logger.info("getFuyinExpressInfo, request ExpressName is null");
            response.setResultCodeAndMessage("3001", "请求express_name为空");
            return response;
        }
        
        if (StringUtils.isBlank(applyRequest.getExpressOrderNo())) {
            logger.info("getFuyinExpressInfo, request ExpressOrderNo is null");
            response.setResultCodeAndMessage("3001", "请求express_order_no为空");
            return response;
        }

        // 调用"快递鸟"查询快递信息，接口半年需续签一次。账号密码：18825179918 / yunyi2017
        KdniaoTrackQueryAPI api = new KdniaoTrackQueryAPI();
        try {
            String result = api.getOrderTracesByJson(applyRequest.getExpressName(), applyRequest.getExpressOrderNo());
            logger.info("getFuyinExpressInfo, result=" + result);
            response.setResultCodeAndMessage("0", "查询快递信息成功");
            response.setResult(result);
            return response;
        } catch (Exception e) {
            logger.error("查询快递信息失败", e);
            response.setResultCodeAndMessage("-1", "查询快递信息失败");
            return response;
        }
    }
    
    /**
     * yyt.clinic.fuyin.apply.cancel -复印取消申请
     * @param data
     * @param sessionId
     * @return
     */
    public Response cancelFuyinApply(String data, String sessionId) {
        logger.info("cancelFuyinApply, request data=" + data + ", sessionId=" + sessionId);
        Response response = new Response();
        FuyinApplyRequest applyRequest = JsonUtils.parseObject(data, FuyinApplyRequest.class);
        if (StringUtils.isBlank(applyRequest.getOrderNo())) {
            logger.info("cancelFuyinApply, request OrderNo is null");
            response.setResultCodeAndMessage("3001", "请求order_no为空");
            return response;
        }

        FuyinApply fa = new FuyinApply();
        fa.setOrderNo(applyRequest.getOrderNo());
        List<FuyinApply> records = fuyinApplyDao.select(fa);
        if (records != null && records.size() > 0) {
            FuyinApply record = records.get(0);

            String orderNo=applyRequest.getOrderNo();
            Map<String, String> updateMap = new HashMap<String, String>();
            updateMap.put("order_no", orderNo);
            logger.info("复印取消申请, 订单号" + orderNo + ", 调base模块, 查询订单信息入参request=" + JSONObject.toJSONString(updateMap));
            Response ordResponse = BaseService.callUnderlineFromInternal("yyt.base.order.by.order.no.out.get",
                    JsonUtils.toJsonString(updateMap));
            logger.info(
                    "复印取消申请, 订单号" + orderNo + ", 调base模块, 查询订单信息返回response=" + JSONObject.toJSONString(ordResponse));
            if (!"0".equals(ordResponse.getResultCode())) {
                logger.info("复印取消申请, 订单号" + orderNo + ", 调base模块, 查询订单信息失败，未找到对应的订单信息");
            }
            OrderExtVo order = JsonUtils.parseObject(ordResponse.getResult(), OrderExtVo.class);

            if (record.getPayStatus().intValue() == 1 && record.getApplyStatus().intValue() == 0) {
                Map<String, Object> map = new HashMap<>();
                map.put("app_id", record.getAppId());

                if (order.getPayMode() != null) {
                    if (order.getPayMode().intValue() == 16) {
                        map.put("pay_code", "WECHATMEDICAL");
                        map.put("order_type", order.getOrderType().intValue() == 1 ? "REGPAY" : "DIAGPAY");
                        map.put("is_insurance", order.getIsInsurance().intValue() == 1 ? "YEP" : "NOPE");
                    } else if (order.getPayMode() == 2 || (order.getPayMode() > 20 && order.getPayMode() < 30)) {
                        map.put("pay_code", "ALIPAY");
                    } else if (order.getPayMode() == 1 || (order.getPayMode() > 10 && order.getPayMode() < 20)) {
                        map.put("pay_code", "WECHAT");
                    } else if (order.getPayMode() == 8) {
                        map.put("pay_code", "PACITY");
                    } else if (order.getPayMode() == 31) {
                        map.put("app_code", order.getPlatformOrgAppCode());
                        map.put("org_code", order.getOrgCode());
                        map.put("pay_code", "HYMEDUNION");
                    } else {
                        throw new RuntimeException("Refund channel unsupported");
                    }
                }

                map.put("order_no", record.getOrderNo());
                map.put("total_fee", String.valueOf(record.getPayFee().intValue()));
                map.put("refund_fee", String.valueOf(record.getPayFee().intValue()));
                logger.info("cancelFuyinApply, map=" + JSON.toJSONString(map));
                // 调用通用退费接口
                Response res = PayService.callUnderlineFromInternal("yyt.pay.unified.refund", JSON.toJSONString(map));
                logger.info("cancelFuyinApply, res=" + JSON.toJSONString(res));
                if ("0".equals(res.getResultCode())) {
                    try {
                        Map<String, Object> paramMap = new HashMap<String, Object>();
                        // 已退费
                        paramMap.put("payStatus", "7");
                        paramMap.put("orderNo", record.getOrderNo());
                        paramMap.put("refundFee", record.getPayFee().intValue());
                        paramMap.put("payContent", "用户取消订单");
                        logger.info("updateFuyinPayStatus, paramMap=" + JSONObject.toJSONString(paramMap));
                        fuyinApplyDao.updateByOrderNo(paramMap);
                        
                        //更新订单状态为取消，支付状态为已退费
                        order.setPayStatus((short)7);
                        order.setOrderStatus((short)7);
                        logger.info("复印取消申请, 订单号" + orderNo + ", 调base模块, 更新订单信息入参request=" + JSONObject.toJSONString(order));
                        BaseService.callUnderlineFromInternal("yyt.base.order.update", JsonUtils.toJsonString(order));

                        response.setResultCodeAndMessage("0", "退费成功");
                    } catch (Exception ex) {
                        logger.error("error", ex);
                        response.setResultCodeAndMessage("-1", "退费成功，更新订单状态失败");
                        return response;
                    }
                } else {
                    response.setResultCodeAndMessage("-1", "退费失败");
                }
            } else {
                response.setResultCodeAndMessage("-1", "取消失败");
            }
        }
        return response;
    }
    
    /**
     * yyt.clinic.fuyin.exception.apply.list -复印所有未处理申请
     * @param data
     * @param sessionId
     * @return
     */
    public Response listFuyinExceptionApply(String data, String sessionId) {
        logger.info("listFuyinExceptionApply, request data=" + data + ", sessionId=" + sessionId);
        Response response = new Response();
//        if (!"1".equals(CacheService.getSessionKey(sessionId, "clinic:fuyin:isLogin"))) {
//            response.setResultCodeAndMessage("3006", "操作失败，请先登录。");
//            return response;
//        }
        FuyinApplyRequest applyRequest = JsonUtils.parseObject(data, FuyinApplyRequest.class);
        if (applyRequest.getPageSize() == null) {
            logger.info("listFuyinExceptionApply, request PageSize is null");
            response.setResultCodeAndMessage("3001", "请求page_size为空");
            return response;
        }
        
        if (applyRequest.getPageNum() == null) {
            logger.info("listFuyinExceptionApply, request PageNum is null");
            response.setResultCodeAndMessage("3001", "请求page_num为空");
            return response;
        }
        
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("pageSize", applyRequest.getPageSize());
        paramMap.put("pageNum", applyRequest.getPageNum());
        if (StringUtils.isNotBlank(applyRequest.getBeginTime())) {
            paramMap.put("beginTime", applyRequest.getBeginTime());
        }
        if (StringUtils.isNotBlank(applyRequest.getEndTime())) {
            paramMap.put("endTime", applyRequest.getEndTime());
        }
        paramMap.put("applyStatus", applyRequest.getApplyStatus());
        paramMap.put("payStatus", applyRequest.getPayStatus());
        if (StringUtils.isNotBlank(applyRequest.getOrderNo())) {
            paramMap.put("orderNo", applyRequest.getOrderNo());
        }
        if (StringUtils.isNotBlank(applyRequest.getAgtOrderNum())) {
            paramMap.put("agtOrderNum", applyRequest.getAgtOrderNum());
        }
        if (StringUtils.isNotBlank(applyRequest.getPatName())) {
            paramMap.put("patName", applyRequest.getPatName());
        }
        if (StringUtils.isNotBlank(applyRequest.getAdmissionNo())) {
            paramMap.put("admissionNo", applyRequest.getAdmissionNo());
        }
        if (StringUtils.isNotBlank(applyRequest.getHospitalCode())) {
            paramMap.put("hospitalCode", applyRequest.getHospitalCode());
        }
        logger.info("listFuyinExceptionApply, applyRequest=" + JsonUtils.toJsonString(applyRequest));
        logger.info("listFuyinExceptionApply, paramMap=" + JsonUtils.toJsonString(paramMap));
        List<FuyinApply> list = fuyinApplyDao.selectException(paramMap);
        logger.info("listFuyinExceptionApply, list=" + JsonUtils.toJsonString(list));
        
        Long count = fuyinApplyDao.selectExceptionCount(paramMap);
        logger.info("listFuyinExceptionApply, count=" + count);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("list", JsonUtils.toJsonString(list));
        resultMap.put("page_size", applyRequest.getPageSize());
        resultMap.put("page_num", applyRequest.getPageNum());
        resultMap.put("count", count);
        response.setResult(JsonUtils.toJsonString(resultMap));
        return response;
    }



    /**
     * yyt.clinic.fuyin.apply.content.update -更新留言内容
     * @param data
     * @return
     */
    public Response updateFuyinApplyContent(String data) {
        logger.info("updateFuyinApplyContent, request data={}" , data);
        Response response = new Response();
        FuyinApply updateFuyinApply = JsonUtils.parseObject(data,FuyinApply.class);
        if (StringUtils.isBlank(updateFuyinApply.getApplyId())){
            response.setResultCodeAndMessage("3001","apply_id不能为空");
            return response;
        }
        fuyinApplyDao.update(updateFuyinApply);
        response.setResultCodeAndMessage("0","更新留言成功");
        return response;
    }

    /**
     * 日期段内的交易流水记录 导出excel
     * yyt.clinic.fuyin.order.record.download -下载订单记录
     *
     * @param data
     * @return
     */
    public ResponseObject downloadFuyinOrderRecord(String data) {
        ResponseObject response = new ResponseObject();
        try {
            logger.info("病案复印对账导出excel原始入参 data ={}", data);
            FuyinApplyRequest applyRequest = JsonUtils.parseObject(data, FuyinApplyRequest.class);
            if (applyRequest.getPageSize() == null) {
                logger.info("listUntreatedApply, request PageSize is null");
                response.setResultCodeAndMessage("3001", "请求page_size为空");
                return response;
            }

            if (applyRequest.getPageNum() == null) {
                logger.info("listUntreatedApply, request PageNum is null");
                response.setResultCodeAndMessage("3001", "请求page_num为空");
                return response;
            }

            Map<String, Object> paramMap = new HashMap<String, Object>();
            if (StringUtils.isNotBlank(applyRequest.getBeginTime())) {
                paramMap.put("beginTime", applyRequest.getBeginTime());
            }
            if (StringUtils.isNotBlank(applyRequest.getEndTime())) {
                paramMap.put("endTime", applyRequest.getEndTime());
            }
            paramMap.put("applyStatus", applyRequest.getApplyStatus());
            paramMap.put("payStatus", applyRequest.getPayStatus());
            if (StringUtils.isNotBlank(applyRequest.getOrderNo())) {
                paramMap.put("orderNo", applyRequest.getOrderNo());
            }
            if (StringUtils.isNotBlank(applyRequest.getAgtOrderNum())) {
                paramMap.put("agtOrderNum", applyRequest.getAgtOrderNum());
            }
            if (StringUtils.isNotBlank(applyRequest.getPatName())) {
                paramMap.put("patName", applyRequest.getPatName());
            }
            if (StringUtils.isNotBlank(applyRequest.getAdmissionNo())) {
                paramMap.put("admissionNo", applyRequest.getAdmissionNo());
            }
            if (StringUtils.isNotBlank(applyRequest.getHospitalCode())) {
                paramMap.put("hospitalCode", applyRequest.getHospitalCode());
            }
            logger.info("listTreatedApply, applyRequest=" + JsonUtils.toJsonString(applyRequest));
            logger.info("listTreatedApply, paramMap=" + JsonUtils.toJsonString(paramMap));
            List<FuyinApply> fuyinApplyList = fuyinApplyDao.selectTreated(paramMap);
            logger.info("listTreatedApply, list=" + JsonUtils.toJsonString(fuyinApplyList));
            Map<String,String> copyItemMap = JsonUtils.parseObject(copyJson,Map.class);
            Map<Integer,String> recieveTypeMap = JsonUtils.parseObject(RECEIVE_TYPE,Map.class);
            Map<Integer,String> useForMap = JsonUtils.parseObject(USE_FOR,Map.class);
            Map<Integer,String> applyStatusMap = JsonUtils.parseObject(APPLY_STATUS,Map.class);
            Map<Integer,String> payStatusMap = JsonUtils.parseObject(PAY_STATUS,Map.class);

            Map<String, Object> result = new HashMap<>();
            if (!CollectionUtils.isEmpty(fuyinApplyList)) {
                List<Map<String, Object>> vos = new ArrayList<>();
                for (FuyinApply fuyinApply : fuyinApplyList) {
                    StringBuilder copyCheckedItemBuilder = new StringBuilder();
                    Map<String, Object> map = new HashedMap();
                    map.put("order_no", fuyinApply.getOrderNo());
                    map.put("copy_count", fuyinApply.getCopyCount());
                    map.put("admission_no", fuyinApply.getAdmissionNo());
                    map.put("pat_name", fuyinApply.getPatName());
                    map.put("admission_dept_name", fuyinApply.getAdmissionDeptName());
                    map.put("admission_begin_time", fuyinApply.getAdmissionBeginTime());
                    map.put("admission_end_time", fuyinApply.getAdmissionEndTime());
                    map.put("apply_user_name", fuyinApply.getApplyUserName());
                    map.put("apply_user_mobile", fuyinApply.getApplyUserMobile());

                    if (fuyinApply.getCheckedItems()!=null){
                       String[] checkedItems = fuyinApply.getCheckedItems().split(",");
                        for (String item :checkedItems){
                            copyCheckedItemBuilder.append(copyItemMap.get(item)).append(",");
                        }
                        map.put("checked_items", copyCheckedItemBuilder.toString());
                    }
                    map.put("express_address", fuyinApply.getExpressAddress());

                    if (fuyinApply.getReceiveType()!=null){
                        map.put("receive_type", recieveTypeMap.get(String.valueOf(fuyinApply.getReceiveType())));
                    }

                    if(fuyinApply.getPayFee() !=null){
                        map.put("pay_fee", fuyinApply.getPayFee()/100f);
                    }

                    map.put("apply_time", fuyinApply.getApplyTime());

                    map.put("use_for", useForMap.get(String.valueOf(fuyinApply.getUseFor())));
                    map.put("approval_by", fuyinApply.getApprovalBy());
                    map.put("apply_status", applyStatusMap.get(String.valueOf(fuyinApply.getApplyStatus())));
                    if (fuyinApply.getRefundFee() !=null){
                        map.put("refund_fee", fuyinApply.getRefundFee()/100f);
                    }
                    if (fuyinApply.getExpressFee() !=null){
                        map.put("express_fee", fuyinApply.getExpressFee()/100f);
                    }
                    if (fuyinApply.getFuyinFee() !=null){
                        map.put("fuyin_fee", fuyinApply.getFuyinFee()/100f);
                    }
                    if (fuyinApply.getFuyinFee() !=null){
                        map.put("fuyin_fee", fuyinApply.getFuyinFee()/100f);
                    }
                    map.put("apply_content",fuyinApply.getApplyContent() );
                    map.put("express_name",fuyinApply.getExpressName() );
                    map.put("express_order_no",fuyinApply.getExpressOrderNo() );
                    map.put("pay_status",payStatusMap.get(String.valueOf(fuyinApply.getPayStatus())));
                    map.put("agt_order_num",fuyinApply.getAgtOrderNum() );



                    vos.add(map);
                }
                result.put("list", vos);

                JSONArray ja = JSONArray.parseArray(JsonUtils.toJsonString(vos));
                Map<String, String> headMap = new LinkedHashMap<String, String>();
                headMap.put("order_no", "订单号");
                headMap.put("copy_count", "病案复印份数");
                headMap.put("admission_no", "住院号");
                headMap.put("pat_name", "患者");
                headMap.put("admission_dept_name", "住院科室");
                headMap.put("admission_begin_time", "入院时间");
                headMap.put("admission_end_time", "出院时间");
                headMap.put("apply_user_name", "申请人");
                headMap.put("apply_user_mobile", "手机号");
                headMap.put("checked_items", "复印项目");
                headMap.put("receive_type", "领取方式");
                headMap.put("express_address", "邮寄地址");
                headMap.put("pay_fee", "支付费用");
                headMap.put("apply_time", "申请时间");
                headMap.put("use_for", "复印用途");
                headMap.put("approval_by", "证件审核批准帐号");
                headMap.put("apply_status", "审核状态");
                headMap.put("refund_fee", "退费费用");
                headMap.put("express_fee", "快递金额");
                headMap.put("fuyin_fee", "复印金额");
                headMap.put("apply_content", "通过/不通过理由");
                headMap.put("express_name", "快递公司");
                headMap.put("express_order_no", "快递订单号");
                headMap.put("pay_status", "支付状态");
                headMap.put("agt_order_num", "收支机构订单号");

                String title = "已完成订单报表";

                String savePath = yaml.getProperty(Config.CONFIG_PAY_ALIPAY_CHECK_ACCOUNT_PATH);
                String fileName = "已完成订单.xlsx";
                String filePath = URLDecoder.decode(savePath + fileName, "UTF-8");
                OutputStream outXlsx = new FileOutputStream(filePath);
                Date d2 = new Date();
                ExcelUtil.exportExcelX(title, headMap, ja, null, 0, outXlsx);
                logger.info("共" + vos.size() + "条数据,执行" + (new Date().getTime() - d2.getTime()) + "ms");
                outXlsx.close();

                com.qiniu.http.Response upres = QiniuService.upload(filePath, fileName, Config.QINIU_BUCKET_FOR_FINANCEEXCEL);
                if (upres.isOK() || upres.statusCode == 614) {
                    logger.info("upload Excel file success!");
                    String bucketURL = yaml.getProperty(Config.QINIU_FINANCE_EXCEL_DOWNLOAD_URL);
                    String path = yaml.getProperty(Config.CONFIG_PAY_ALIPAY_CHECK_ACCOUNT_PATH);

                    String url = QiniuService.download(fileName, path, bucketURL);
                    if (org.apache.commons.lang.StringUtils.isBlank(url)) {
                        return new ResponseObject().buildResultCodeAndMessage("2", "Get FinanceBill Excel Url for online is null !");
                    }

                    return new ResponseObject().buildResultCodeAndMessageAndResult(Response.SUCCESS_CODE, Response.SUCCESS_MESSAGE,
                            new FinanceExcel(url));
                } else {
                    logger.info("financeExcel_qiniu_upload_fail!!");
                    return new ResponseObject().buildResultCodeAndMessage("2", "失败");
                }
            }
        } catch (Exception e) {
            logger.error("病案复印系统异常errMsg={}",e);
        }
        return response;
    }


}
